package com.py.credit.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.CreditSearchEnum;
import com.py.credit.service.CreditSearchService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.entity.SysOfficeEntity;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/creditSearch")
public class CreditSearchController {

	private final static String FRONT_TABLE_ID = "creditSearch_";

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@Autowired
	private CreditSearchService creditSearchService;
	

	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "deptId", defaultValue = "", required = false) Long deptId,
			@RequestParam(value = "ywId", defaultValue = "", required = false) String ywId,
			@RequestParam(value = "ztType", defaultValue = "", required = false) String ztType,
			@RequestParam(value = "condition", defaultValue = "", required = false) String condition, Page page,
			HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}

		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID + ywId);
		String[] additionalColumns = { "id" };
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? CreditSearchEnum.getDefaultShowColumnEN()
				: Arrays.asList(configColumns);

		List<Map<String, Object>> tableList = new ArrayList<>();
				
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();

		try {
			Map<String, Object> modelMap = creditSearchService.getModelByOffice(ywId, deptId, ztType);

			double showScore = 0;

			if (modelMap != null && modelMap.get("modelId") != null) {

				Object obj = modelMap.get("showScoreLine");
				if (null != obj && !"".equals(obj)) {
					String temp = String.valueOf(modelMap.get("showScoreLine"));
					if (!StringUtils.isEmpty(temp)) {
						showScore = Double.parseDouble(temp);
					}
				}

				tableList = creditSearchService.getByConditionForPage(String.valueOf(modelMap.get("modelId")),
						showScore, showColumns, additionalColumns, condition, page);
				
			}
			r.setData(tableList);
			r.setCount(page.getTotalCount());
			r.setCode(RestServiceResult.CODE_SUCCESS);
			// else {
			// tableList = creditSearchService.get2ByConditionForPage(showScore ,
			// showColumns, additionalColumns, condition, page);
			// }
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常！");
		}
		return r;
	}

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(CreditSearchEnum.getOptionalColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getDrqydfAdvancedConditionColumns() {
		return new RestServiceResult<List<OptionalColumn>>(CreditSearchEnum.getAdvancedConditionColumns());

	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "ywId", defaultValue = "", required = false) String ywId,@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("CreditSearchController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}

			String column = StringUtils.join(columns, ",");
			MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID + ywId, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}

	@RequestMapping(value = "/export.json")
    public void export(
    		@RequestParam(value = "deptId", defaultValue = "", required = false) Long deptId,
			@RequestParam(value = "ywId", defaultValue = "", required = false) String ywId,
			@RequestParam(value = "ztType", defaultValue = "", required = false) String ztType,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
            Page page,HttpServletResponse response,HttpServletRequest request) throws IOException {
    	
    	RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo) {
	            ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
	            throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        List<String> columns = JSONArray.parseArray(columnEN, String.class);
        List<OptionalColumn> optionalColumns = CreditSearchEnum.getOptionalColumns();
        List<Map<String, Object>> data = new ArrayList<>();
        try {
			Map<String, Object> modelMap = creditSearchService.getModelByOffice(ywId, deptId, ztType);

			double showScore = 0;

			if (modelMap != null && modelMap.get("modelId") != null) {

				Object obj = modelMap.get("showScoreLine");
				if (null != obj && !"".equals(obj)) {
					String temp = String.valueOf(modelMap.get("showScoreLine"));
					if (!StringUtils.isEmpty(temp)) {
						showScore = Double.parseDouble(temp);
					}
				}
				
				page.setLimit(1000);
		        
		        data = creditSearchService.getByConditionForPage(String.valueOf(modelMap.get("modelId")),
		        		showScore,columns, null, condition,page);
		        ExcelUtil.downloadExcel(response, data, "主体信用分记录", "主体信用分记录", columns, optionalColumns);
			}else {
				ExcelUtil.downloadExcel(response, data, "主体信用分记录", "主体信用分记录", columns, optionalColumns);
			}

		} catch (Exception e) {
			throw new ServiceException("系统异常，请稍后再试！");
		}
        
    }
	
	@RequestMapping(value = "/getBumeng.json")
	public RestServiceResult<List<Map<String, Object>>> getBumeng(
			@RequestParam(value = "ywId", defaultValue = "", required = true) String ywId,
			@RequestParam(value = "mainType", defaultValue = "", required = false) String mainType,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		try {
			
			String token = HttpServletHelper.getUserToken(request);
			// 获取当前用户信息
			RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
			SysUser userInfo = null;
			if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
				userInfo = user.getData();
				if (null == userInfo || userInfo.getId() <= 0) {
					result.setCode(RestServiceResult.CODE_UNKNOW);
					result.setMsg("系统异常，请稍后再试！");
					ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
					return result;
				}
			} else {
				result.setCode(user.getCode());
				result.setMsg(user.getMsg());
				return result;
			}
			
			int i  = userInfo.getUserType();
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if(i == 3 || i == 5 || i == 2){
				List<String> bumengList = creditSearchService.getBumeng(ywId, mainType);
				for(String bumeng: bumengList){
					if(bumeng != null && !"".equals(bumeng)){
						RestServiceResult<SysOfficeEntity> rsysOfficeEntity = xypjRemoteBaseService.getOfficesById(Long.parseLong(bumeng));
						SysOfficeEntity sysOfficeEntity = null;
						if (RestServiceResult.CODE_SUCCESS == rsysOfficeEntity.getCode()) {
							sysOfficeEntity = rsysOfficeEntity.getData();
							if (null != sysOfficeEntity) {
								
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("id", sysOfficeEntity.getId());
								map.put("name", sysOfficeEntity.getOfficeName());
								list.add(map);
							}
						} else {
							result.setCode(user.getCode());
							result.setMsg(user.getMsg());
							return result;
						}
					}
				}
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("id", "");
//				map.put("name", "公共");
//				list.add(map);
			}else {
				long officeId = 0;
				String officeName = "";
				if(0 == userInfo.getParentId()){
					 officeId = userInfo.getOfficeId();
					 officeName = userInfo.getOfficeName();
				}else{
					officeId = userInfo.getParentId();
					RestServiceResult<SysOfficeEntity> rsysOfficeEntity = xypjRemoteBaseService.getOfficesById(officeId);
					SysOfficeEntity sysOfficeEntity = rsysOfficeEntity.getData();
					officeName = sysOfficeEntity.getOfficeName();
				}
				
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", officeId);
				map.put("name", officeName);
				list.add(map);
				
			}
			result.setData(list);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常");
		}
		return result;
	}
}
